<template>
  <div class="table_container">
    <Table
      ref="table"
      border
      :height="dealHeight"
      :loading="loading"
      :columns="dealColumns"
      :data="showData"
      show-summary
      :summary-method="handleSummary"
      :span-method="handleSpan"
    >
    </Table>
    <Page
      ref="page"
      class="page"
      :page-size-opts="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      size="small"
      @on-change="changePage"
      show-sizer
      @on-page-size-change="pageSizeChange"
    />
  </div>
</template>
<script>
import {
  addCategoryHeader,
  flattenData,
  addRenderToColumns,
  addNewChildrenToLowestLevel,
  getMergeNum,
  getMaxLevelHeader,
  getColumnSumData,
  removeNullChildren,
  addAlignToObjects
} from '../utils/util'
export default {
  data() {
    return {
      loading: true,
      pageSize: this.fgState === '审核通过' || this.fgState === '待审核' ? 50 : 10,
      dealColumns: [],
      pageIndex: 1,
      showData: [],
      dealData: [],
      spanArr: {
        columnArr1: [],
        columnArr2: [],
        columnArr3: [],
        columnArr4: []
      } // 合并单元格
    }
  },
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    data: {
      type: Array,
      default: () => []
    },
    total: {
      type: Number,
      default: 0
    },
    height: {
      type: Number,
      default: 270
    },
    shouldFetch: {
      type: Boolean,
      default: false
    },
    fgState: {
      // 状态为待提交才能输入修改
      type: String,
      default: ''
    },
    tabKey: {
      type: String,
      default: 'coverStatus'
    },
    id: {
      type: String,
      default: ''
    }
  },
  watch: {
    columns: {
      handler() {
        this.handleData()
      }
    }
  },
  computed: {
    canEdit() {
      return this.fgState !== '审核通过' && this.fgState !== '待审核'
    },
    dealHeight() {
      const h = window.innerHeight - this.height
      return h < 450 ? 450 : h
    }
  },
  mounted() {
    this.handleData()
  },
  methods: {
    handleData() {
      if (this.data.length <= 0) {
        return
      }
      //生成数据列的表头
      this.dealColumns = removeNullChildren(this.columns)
      this.dealColumns = addAlignToObjects(this.dealColumns)
      const sumData = getColumnSumData(this.data)
      // 表头圈圈ICON
      this.dealColumns = addNewChildrenToLowestLevel(this.dealColumns, sumData)
      // 关键业务环节 列
      const firstHeader = getMaxLevelHeader(this.data)
      // firstHeader.children.pop()
      // 一级分类 列
      let sort = addCategoryHeader(this.dealColumns)
      // 整合关键业务环节、一级分类、数据列
      this.dealColumns.unshift(firstHeader, sort)

      //生成行数据，如果数据status是1、2、3的给数据加cellClassName
      this.dealData = flattenData(this.data)

      // 最后再渲染输入框
      this.showData = this.dealData.slice(this.pageSize * (this.pageIndex - 1), this.pageSize * this.pageIndex)
      this.dealColumns = addRenderToColumns(
        this.dealColumns,
        () => this.showData,
        this.canEdit,
        this.data,
        this.$refs.page
      )
      // 动态合并表格
      this.spanArr.columnArr1 = getMergeNum(this.showData, 'level1')
      this.spanArr.columnArr2 = getMergeNum(this.showData, 'level2')
      this.spanArr.columnArr3 = getMergeNum(this.showData, 'level3')
      this.spanArr.columnArr4 = getMergeNum(this.showData, 'level4')

      this.loading = false
    },
    handleSummary({ columns, data }) {
      const sums = {}
      columns.forEach((column, index) => {
        const key = column.key
        if (index === 0) {
          sums[key] = {
            key,
            value: '数字化应用业务实体覆盖数'
          }
          return
        }
        // 去掉序号计算
        if (key === 'orderNum' || key === 'app') {
          sums[key] = {
            key,
            value: ''
          }
          return
        }
        let values = []
        for (let i = 0; i < this.data.length; i++) {
          let item = this.data[i]
          let num = this.dealData[i]
          if (item[key]?.status !== 2) {
            values.push(Number(num[key]))
          }
        }
        // this.data.forEach(item => {
        //   if(item[key].status !== 2){
        //     values.push(Number(item[key].value))
        //   }
        // })
        // const values = this.dealData.map(item => Number(item[key]))
        if (!values.every(value => isNaN(value))) {
          const v = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[key] = {
            key,
            value: v
          }
        } else {
          sums[key] = {
            key,
            value: 0
          }
        }
      })
      return sums
    },
    handleSpan({ row, column, rowIndex, columnIndex }) {
      if (column.key === 'level1') {
        // 二维数组存储的数据 取出
        const _row = this.spanArr.columnArr1[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
        //不可以return {rowspan：0， colspan: 0} 会造成数据不渲染
      } else if (column.key === 'level2') {
        const _row = this.spanArr.columnArr2[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      } else if (column.key === 'level3') {
        const _row = this.spanArr.columnArr3[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      } else if (column.key === 'level4') {
        const _row = this.spanArr.columnArr4[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      } else {
        return false
      }
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize
      this.changePage(1)
    },
    changePage(pageIndex) {
      // this.loading = true
      this.pageIndex = pageIndex
      // this.$emit('changePage', pageIndex, this.pageSize)
      this.showData = this.dealData.slice(this.pageSize * (this.pageIndex - 1), this.pageSize * this.pageIndex)
      this.dealColumns = addRenderToColumns(
        this.dealColumns,
        () => this.showData,
        this.canEdit,
        this.data,
        this.$refs.page
      )

      // 动态合并表格
      this.spanArr.columnArr1 = getMergeNum(this.showData, 'level1')
      this.spanArr.columnArr2 = getMergeNum(this.showData, 'level2')
      this.spanArr.columnArr3 = getMergeNum(this.showData, 'level3')
      this.spanArr.columnArr4 = getMergeNum(this.showData, 'level4')
      this.$nextTick(() => {
        this.loading = false
        // 翻页 滚动到顶部
        setTimeout(() => {
          //这里要延迟下滚动
          document.getElementsByClassName('ivu-table-body')[0].scroll(0, 0)
        }, 2000)
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ivu-table-fixed {
  pointer-events: none;
}

/deep/.ivu-table-fixed-header {
  pointer-events: all;
}

/deep/.ivu-table-fixed-body {
  pointer-events: all;
}
/deep/.ivu-table .ivu-table-body tbody tr td:last-child {
  padding-right: 0 !important;
}
.table_container {
  /deep/.ivu-table .ivu-table-header thead tr th {
    padding-right: 0 !important;
  }
}

/deep/.ivu-table .ivu-table-body .green {
  background: #00d966;
  color: #000;
}
/deep/.ivu-table .ivu-table-body .red {
  background: #ff5e64;
  color: #000;
}
/deep/.ivu-table .ivu-table-body .yellow {
  background: #ffb77c;
  color: #000;
}
.page {
  text-align: end;
  padding: 10px;
}
</style>
